package com.prs.crm.action.document.report;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.aspectj.internal.lang.annotation.ajcDeclareAnnotation;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import sun.java2d.pipe.SpanShapeRenderer.Simple;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.context.FileUtil;
import com.prs.crm.domain.approval.JobType;
import com.prs.crm.domain.document.report.ReportFormCenter;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.warning.WarnContent;
import com.prs.crm.service.document.report.ReportFormCenterService;
import com.prs.crm.service.hr.PersonService;
import com.prs.crm.service.warning.WarnContentService;
import com.prs.crm.tools.ControlJMail;
import com.prs.crm.tools.Datetools;
import com.prs.crm.tools.NoteTools;

public class ReportFormCenterAction extends BaseAction{

	private static final long serialVersionUID = 1L;
	private ReportFormCenter reportFormCenter;
	private ReportFormCenterService reportFormCenterService;
	private PaginationSupport pagination;
	private Integer[] ids;
	private Collection<TreeNode> nodes;
	private String reportIds;
	
	private File upload;
	private String uploadFileName;
	private File uploads;
	private String uploadsFileName;
	private PersonService personService;
	private ControlJMail cj=new ControlJMail();
	private NoteTools nt=new NoteTools();
	private Datetools dt=new Datetools();
	private WarnContentService warnContentService;
	
	public WarnContentService getWarnContentService() {
		return warnContentService;
	}
	public void setWarnContentService(WarnContentService warnContentService) {
		this.warnContentService = warnContentService;
	}
	public Datetools getDt() {
		return dt;
	}
	public void setDt(Datetools dt) {
		this.dt = dt;
	}
	public NoteTools getNt() {
		return nt;
	}
	public void setNt(NoteTools nt) {
		this.nt = nt;
	}
	public ControlJMail getCj() {
		return cj;
	}
	public void setCj(ControlJMail cj) {
		this.cj = cj;
	}
	public PersonService getPersonService() {
		return personService;
	}
	public void setPersonService(PersonService personService) {
		this.personService = personService;
	}
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public File getUploads() {
		return uploads;
	}
	public void setUploads(File uploads) {
		this.uploads = uploads;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUploadsFileName() {
		return uploadsFileName;
	}
	public void setUploadsFileName(String uploadsFileName) {
		this.uploadsFileName = uploadsFileName;
	}
	public String getReportIds() {
		return reportIds;
	}
	public void setReportIds(String reportIds) {
		this.reportIds = reportIds;
	}
	public ReportFormCenter getReportFormCenter() {
		return reportFormCenter;
	}
	public void setReportFormCenter(ReportFormCenter reportFormCenter) {
		this.reportFormCenter = reportFormCenter;
	}
	public ReportFormCenterService getReportFormCenterService() {
		return reportFormCenterService;
	}
	public void setReportFormCenterService(
			ReportFormCenterService reportFormCenterService) {
		this.reportFormCenterService = reportFormCenterService;
	}
	public PaginationSupport getPagination() {
		return pagination;
	}
	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}
	public Integer[] getIds() {
		return ids;
	}
	public void setIds(Integer[] ids) {
		this.ids = ids;
	}
	public Collection<TreeNode> getNodes() {
		return nodes;
	}
	public void setNodes(Collection<TreeNode> nodes) {
		this.nodes = nodes;
	}
	
	@Action(value = "loadReportFormCenterTree", results = { @Result(name = "success", type = "json",
			params = {"root", "nodes" }) })
	public String loadReportFormCenterTree(){
		nodes = new ArrayList<TreeNode>();
		Collection<ReportFormCenter> reportFormCenters = this.getReportFormCenterService().getRootReportFormCenter();
		for (ReportFormCenter reportFormCenter : reportFormCenters) {
			if (reportFormCenter.getViState()==1) {
			TreeNode node = new TreeNode();
			node.setId(String.valueOf(reportFormCenter.getId()));
			node.setText(reportFormCenter.getName());
			addChildNode(reportFormCenter, node);
			nodes.add(node);
		}
	}
		return SUCCESS;
	}
	private void addChildNode(ReportFormCenter reportFormCenter,TreeNode parentnode){
		if(reportFormCenter.getChilds()!= null){
		for(ReportFormCenter form:reportFormCenter.getChilds()){
			if (form.getJspPath()==null) {	
				if (reportFormCenter.getViState()==1) {
				TreeNode node = new TreeNode();
				node.setId(String.valueOf(form.getId()));
				node.setText(form.getName());
				parentnode.addChildNode(node);
				addChildNode(form, node);
				}
			}
		}
	}
}
	@Action("selectReportFormCenter")
	public String selectReportFormCenter(){
		Person currorPerson=AppContext.getAccountContext().currentUser();
		List<ReportFormCenter> rfc=this.getReportFormCenterService().getAllReportFormCenter();
		for (ReportFormCenter rf : rfc) {
			if (rf.getRecorder().getId().equals(currorPerson.getId())) {
				rf.setViState(1);
				rf.setUpState(1);
				this.getReportFormCenterService().submit(rf);
			}else{
				if (rf.getVisitPermission()==null || "".equals(rf.getVisitPermission().trim())) {
					rf.setViState(1);//表示有查看权限
					this.getReportFormCenterService().submit(rf);
				}else{
					String[] pers=rf.getVisitPermission().split(",");
					for (String perss : pers) {
						if (currorPerson.getResume().getName().equals(perss)) {
							rf.setViState(1);
							this.getReportFormCenterService().submit(rf);
							break;
						}else{
							rf.setViState(2);//没有查看权限 
							this.getReportFormCenterService().submit(rf);
						}
					}
					break;
				}
				if (rf.getUpdatePermission()==null || "".equals(rf.getUpdatePermission().trim())) {
					rf.setUpState(1);//表示有修改权限
					this.getReportFormCenterService().submit(rf);
				}else{
					String[] upPer=rf.getUpdatePermission().split(",");
					for (String upPers : upPer) {
						if (currorPerson.getResume().getName().equals(upPers)) {
							rf.setUpState(1);//表示有修改权限
							this.getReportFormCenterService().submit(rf);
							break;
						}else{
							rf.setUpState(2);//表示没有修改权限
							this.getReportFormCenterService().submit(rf);
						}
					}
					break;
				}
			}
		}
		return SUCCESS;
	}
	@Action("listReportFormCenter")
	public String listReportFormCenter(){
		Person currorPerson=AppContext.getAccountContext().currentUser();
		List<ReportFormCenter> rfc=this.getReportFormCenterService().getAllReportFormCenter();
		for (ReportFormCenter rf : rfc) {
//			System.out.println(rf.getName());
			if (rf.getRecorder().getId().equals(currorPerson.getId())) {
				rf.setViState(1);
				rf.setUpState(1);
				this.getReportFormCenterService().submit(rf);
			}else{
				if (rf.getVisitPermission()==null || "".equals(rf.getVisitPermission().trim())) {
					rf.setViState(1);//表示有查看权限
					this.getReportFormCenterService().submit(rf);
				}else{
					String[] pers=rf.getVisitPermission().split(",");
					for (String perss : pers) {
						if (currorPerson.getResume().getName().equals(perss)) {
							rf.setViState(1);
							this.getReportFormCenterService().submit(rf);
							break;
						}else{
							rf.setViState(2);//没有查看权限 
							this.getReportFormCenterService().submit(rf);
						}
					}
				}
				if (rf.getUpdatePermission()==null || "".equals(rf.getUpdatePermission().trim())) {
					rf.setUpState(1);//表示有修改权限
					this.getReportFormCenterService().submit(rf);
				}else{
					String[] upPer=rf.getUpdatePermission().split(",");
					for (String upPers : upPer) {
						if (currorPerson.getResume().getName().equals(upPers)) {
							rf.setUpState(1);//表示有修改权限
							this.getReportFormCenterService().submit(rf);
							break;
						}else{
							rf.setUpState(2);//表示没有修改权限
							this.getReportFormCenterService().submit(rf);
						}
					}
				}
			}
		}
		DetachedCriteria criteria=this.getPaginationHelper().createQuery(ReportFormCenter.class).add(Restrictions.isNull("parent"));
		criteria.add(Restrictions.eq("viState", 1));
//		criteria.add(Restrictions.in("parent", this.getReportFormCenterService().convertToReport(reportIds)));
		pagination=this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getReportFormCenterService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	@Action("listReportFormCenters")
	public String listReportFormCenters(){
		Person currorPerson=AppContext.getAccountContext().currentUser();
		List<ReportFormCenter> rfc=this.getReportFormCenterService().getAllReportFormCenter();
		for (ReportFormCenter rf : rfc) {
			if (rf.getRecorder().getId().equals(currorPerson.getId())) {
				rf.setViState(1);
				rf.setUpState(1);
				this.getReportFormCenterService().submit(rf);
			}else{
				if (rf.getVisitPermission()==null || "".equals(rf.getVisitPermission().trim())) {
					rf.setViState(1);//表示有查看权限
					this.getReportFormCenterService().submit(rf);
				}else{
					String[] pers=rf.getVisitPermission().split(",");
					for (String perss : pers) {
						if (currorPerson.getResume().getName().equals(perss)) {
							rf.setViState(1);
							this.getReportFormCenterService().submit(rf);
							break;
						}else{
							rf.setViState(2);//没有查看权限 
							this.getReportFormCenterService().submit(rf);
						}
					}
				}
				if (rf.getUpdatePermission()==null || "".equals(rf.getUpdatePermission().trim())) {
					rf.setUpState(1);//表示有修改权限
					this.getReportFormCenterService().submit(rf);
				}else{
					String[] upPer=rf.getUpdatePermission().split(",");
					for (String upPers : upPer) {
						if (currorPerson.getResume().getName().equals(upPers)) {
							rf.setUpState(1);//表示有修改权限
							this.getReportFormCenterService().submit(rf);
							break;
						}else{
							rf.setUpState(2);//表示没有修改权限
							this.getReportFormCenterService().submit(rf);
						}
					}
				}
			}
		}
		DetachedCriteria criteria=this.getPaginationHelper().createQuery(ReportFormCenter.class).add(Restrictions.isNotNull("parent")).add(Restrictions.eq("parent",reportFormCenter));
		pagination=this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.eq("viState", 1));
		this.setPagination(this.getReportFormCenterService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	@Action("listReport")
	public String listReport(){
		DetachedCriteria criteria=this.getPaginationHelper().createQuery(ReportFormCenter.class);
		pagination=this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getReportFormCenterService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	@Action("editAddFile")
	public String editAddFile(){
		return SUCCESS;
	}
	
	@Action("editReportFileSet")
	public String editReportFileSet(){
		return SUCCESS;
	}
	
	@Action("editRenameFile")
	public String editRenameFile(){
		return SUCCESS;
	}
	@Action(value="saveAddFile",results={
			@Result(name="success",type="redirect",location="selectReportFormCenter"),
			@Result(name="error",type="chain",location="editAddFile")
	})
	public String saveAddFile(){
		if (reportFormCenter.getName()==null || "".equals(reportFormCenter.getName().trim())) {
			addActionError("文件夹名称不能为空！");
			return ERROR;
		}
		this.getReportFormCenterService().save(reportFormCenter);
		if (reportFormCenter.getId()!=null) {
		if ("给指定人员发邮件".equals(reportFormCenter.getUpdateSet())) {
			String[] perId=reportFormCenter.getAppiontPersonId().split(",");
			for (String per : perId) {
				Person person=this.getPersonService().getPersonById(Integer.parseInt(per));
				Person curper=AppContext.getAccountContext().getUser();
				if (person!=null) {
					cj.sendMail(curper.getResume().getEmail(), person.getResume().getEmail(), person.getLoginCode(), person.getLoginPwd(), "文件夹创建成功", "文件夹"+reportFormCenter.getName()+"创建成功");
				}
			}
		}
		if ("给指定人员发送手机短信".equals(reportFormCenter.getUpdateSet())) {
			String[] perId=reportFormCenter.getAppiontPersonId().split(",");
			for (String per : perId) {
				Person person=this.getPersonService().getPersonById(Integer.parseInt(per));
				if (person!=null) {
					Date date=new Date();
					SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
					try {
						nt.SendNote(person.getResume().getMobile_No(),"文件夹"+reportFormCenter.getName()+"创建成功",sf.format(date));
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}	
				}
			}
		}
		if ("给指定人员发送内部消息".equals(reportFormCenter.getUpdateSet())) {
			String[] perId=reportFormCenter.getAppiontPersonId().split(",");
			for (String per : perId) {
				Person person=this.getPersonService().getPersonById(Integer.parseInt(per));
				Person curper=AppContext.getAccountContext().getUser();
				if (person!=null) {
					Date date=new Date();
					SimpleDateFormat sf=new SimpleDateFormat("yyyyMMddHHmmss");
					 WarnContent wc=new WarnContent();	
			    	 wc.setWarnstyl("文件夹创建成功");
			    	 wc.setWarnCont("文件夹"+reportFormCenter.getName()+"创建成功");
			    	 wc.setReceivID(per);
			    	 wc.setReadState("1");
				     this.getWarnContentService().save(wc);		
				}
			}
		}
		}
		return SUCCESS;
	}
	
	@Action(value="saveRenameFile",results={
			@Result(name="success",type="redirect",location="selectReportFormCenter"),
			@Result(name="error",type="chain",location="editRenameFile")
	})
	public String saveRenameFile(){
		this.getReportFormCenterService().save(reportFormCenter);
		return SUCCESS;
	}
	@Action(value="saveReportFileSet",results={
			@Result(name="success",type="redirect",location="selectReportFormCenter"),
			@Result(name="error",type="chain",location="editReportFileSet")
	})
	public String saveReportFileSet(){
		if (upload!=null) {
			this.reportFormCenter.setAttach(FileUtil.getInstance().createAttach(upload, uploadFileName));
		}
		if (uploads!=null) {
			this.reportFormCenter.setAttach1(FileUtil.getInstance().createAttach(uploads, uploadsFileName));
		}
		if (reportFormCenter.getName()==null || "".equals(reportFormCenter.getName().trim())) {
			addActionError("报表主题不能为空！");
			return ERROR;
		}
		if (reportFormCenter.getJspPath()==null || "".equals(reportFormCenter.getJspPath().trim())) {
			addActionError("jsp路径不能为空！");
			return ERROR;
		}
		this.getReportFormCenterService().save(reportFormCenter);
		return SUCCESS;
	}
	
	@Clew(results={"error"})
	@Action(value="removeReportForm",results={
			@Result(name="success",type="redirect",location="selectReportFormCenter"),
			@Result(name="error",type="redirect",location="selectReportFormCenter")
	})
	public String removeReportForm(){
		if(reportFormCenter.getChilds().size()!=0) {
			this.setPrompt("该文件里面还有模板,不能删除！");
			return ERROR;
		}
		this.getReportFormCenterService().removeReport(reportFormCenter.getId());
		return SUCCESS;
	}
	@Action(value="removeReportForms",results={
			@Result(name="success",type="redirect",location="listReport"),
			@Result(name="error",type="redirect",location="listReport")
	})
	public String removeReportForms(){
		this.getReportFormCenterService().removeReport(reportFormCenter.getId());
		return SUCCESS;
	}
	

	@Action("editRemove")
	public String editRemove(){
		return SUCCESS;
	}
	
	@Action(value="saveRemove",results={
			@Result(name="success",type="redirect",location="selectReportFormCenter"),
			@Result(name="error",type="chain",location="editRemove")
	})
	public String saveRemove(){
		this.getReportFormCenterService().save(reportFormCenter);
		return SUCCESS;
	}
	@Action("listFindReportFormCenter")
	public String listFindReportFormCenter(){
		DetachedCriteria criteria=this.getPaginationHelper().createQuery(ReportFormCenter.class).add(Restrictions.isNull("parent"));
		pagination=this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getReportFormCenterService().listByPage(criteria, pagination));
		return SUCCESS;
	}
	@Action(value="findReportFromcenter",results={
			@Result(name="success",type="redirect",location="listFindReportFormCenter"),
			@Result(name="error",type="redirect",location="listReport")
	})
	public String findReportFromcenter(){
		
		return SUCCESS;
	}
}
